package com.csweimei.rentmanagementtreasure.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.csweimei.rentmanagementtreasure.http.Repository;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.utils.SPUtils;

public class AppConfig {
    public static final int FREE_NUM = 1;

    public static final String BUNDLE_KEY = "postData";
    public static final String BUNDLE_KEY2 = "postData2";

    public static final String VIP_PERSON = "VIP_PERSON";
    public static final String VIP_ENT = "VIP_ENT";
    public static final String APP_NAME = "租管宝";

    public static final String UMENG_KEY = "6698d388940d5a4c499229ae";

    public static final String VIP_URL = "http://privacy.csweimei.cn/wm/vip_service.html?name=";
    public static final String YSZC_URL = "http://privacy.csweimei.cn/wm/demo_zgb.html?name=";
    public static final String YHXY_URL = "http://privacy.csweimei.cn/user/yhxy.html?appname=";


    //WX
    public static final String  WXAPPID = "wx1ea1196944476c99";
    public static final String  WXAPPSECRET = "";

    public static final String  WXPARTNER_ID = "1619746752";
    public static final String  WXAPIKEY = "2sX0ihkKmCWwrsOrpDrFech1A2gioARR";

    public static Map<String,String> getCurMap(Repository repository){
        Map<String,String> map = new HashMap<>();
        if (repository.isLogin()){
            map.put("userid",repository.getLoginInfo().getData().getUser_id()+"");
//            map.put("userid","952593");
        }
        return map;
    }

    public static void setVipPerson(int day){
        SPUtils.getInstance().put(AppConfig.VIP_PERSON,day);
    }

    public static void setVipEnt(int day){
        SPUtils.getInstance().put(AppConfig.VIP_ENT,day);
    }

    public static boolean isPersonVip(){
        if (SPUtils.getInstance().getInt(VIP_PERSON) > 0){
            return true;
        }else {
            return false;
        }
    }

    public static boolean isEntVip(){
        if (SPUtils.getInstance().getInt(VIP_ENT) > 0){
            return true;
        }else {
            return false;
        }
    }



    public static String obtainWeek(String dateTime,String formatDate){
        String week = "";
        Calendar calendar = Calendar.getInstance();
        //如果日期为空，计算当天是周几
        if (TextUtils.isEmpty(dateTime)){
            calendar.setTime(new Date(System.currentTimeMillis()));
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat(formatDate, Locale.getDefault());
            Date date = null;
            try {
                date = sdf.parse(dateTime);
            } catch (Exception e) {
                Log.d("callback","时间解析异常");
            }
            if(date != null){
                calendar.setTime(new Date(date.getTime()));
            }
        }

        switch (calendar.get(Calendar.DAY_OF_WEEK)){
            case 1:
                week = "周日";
                break;
            case 2:
                week = "周一";
                break;
            case 3:
                week = "周二";
                break;
            case 4:
                week = "周三";
                break;
            case 5:
                week = "周四";
                break;
            case 6:
                week = "周五";
                break;
            case 7:
                week = "周六";
                break;

        }
        return week;
    }

    /**
     * 获得设备硬件标识，请务必获取权限：READ_PHONE_STATE
     * @param context 上下文
     * @return 设备硬件标识
     */
    public static String getDeviceId(Context context) {
        StringBuilder sbDeviceId = new StringBuilder();

        //获得设备默认IMEI（>=6.0 需要ReadPhoneState权限）
        String imei = null;
        try {
            imei = getIMEI(context);
        }catch (Exception e){
            e.printStackTrace();
        }
        //获得AndroidId（无需权限）
        String androidid = getAndroidId(context);
        //获得设备序列号（无需权限）
        String serial = getSERIAL();
        //获得硬件uuid（根据硬件相关属性，生成uuid）（无需权限）
        String uuid = getDeviceUUID().replace("-", "");

        //追加imei
        if (imei != null && imei.length() > 0) {
            sbDeviceId.append(imei);
            sbDeviceId.append("|");
        }
        //追加androidid
        if (androidid != null && androidid.length() > 0) {
            sbDeviceId.append(androidid);
            sbDeviceId.append("|");
        }
        //追加serial
        if (serial != null && serial.length() > 0) {
            sbDeviceId.append(serial);
            sbDeviceId.append("|");
        }
        //追加硬件uuid
        if (uuid.length() > 0) {
            sbDeviceId.append(uuid);
        }

        //生成SHA1，统一DeviceId长度
        if (sbDeviceId.length() > 0) {
            try {
                byte[] hash = getHashByString(sbDeviceId.toString());
                String sha1 = bytesToHex(hash);
                if (sha1.length() > 0) {
                    //返回最终的DeviceId
                    return sha1;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        //如果以上硬件标识数据均无法获得，
        //则DeviceId默认使用系统随机数，这样保证DeviceId不为空
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 需要获得READ_PHONE_STATE权限，>=6.0，默认返回null
     * @param context
     * @return
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    private static String getIMEI(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getDeviceId();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 获得设备的AndroidId
     *
     * @param context 上下文
     * @return 设备的AndroidId
     */
    @SuppressLint("HardwareIds")
    private static String getAndroidId(Context context) {
        try {
            return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 获得设备序列号（如：WTK7N16923005607）, 个别设备无法获取
     *
     * @return 设备序列号
     */
    @SuppressLint("HardwareIds")
    private static String getSERIAL() {
        try {
            return Build.SERIAL;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 获得设备硬件uuid
     * 使用硬件信息，计算出一个随机数
     * @return 设备硬件uuid
     */
    @SuppressLint("HardwareIds")
    private static String getDeviceUUID() {
        try {
            String dev = "3883756" +
                    Build.BOARD.length() % 10 +
                    Build.BRAND.length() % 10 +
                    Build.DEVICE.length() % 10 +
                    Build.HARDWARE.length() % 10 +
                    Build.ID.length() % 10 +
                    Build.MODEL.length() % 10 +
                    Build.PRODUCT.length() % 10 +
                    Build.SERIAL.length() % 10;
            return new UUID(dev.hashCode(), Build.SERIAL.hashCode()).toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }

    /**
     * 取SHA1
     * @param data 数据
     * @return 对应的hash值
     */
    private static byte[] getHashByString(String data) {
        try{
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.reset();
            messageDigest.update(data.getBytes(StandardCharsets.UTF_8));
            return messageDigest.digest();
        } catch (Exception e){
            return "".getBytes();
        }
    }

    /**
     * 转16进制字符串
     * @param data 数据
     * @return 16进制字符串
     */
    private static String bytesToHex(byte[] data){
        StringBuilder sb = new StringBuilder();
        String stmp;
        for (byte datum : data) {
            stmp = (Integer.toHexString(datum & 0xFF));
            if (stmp.length() == 1){
                sb.append("0");
            }
            sb.append(stmp);
        }
        return sb.toString().toUpperCase(Locale.CHINA);
    }


}
